//
//  UIColorRGBValueTransformer.m
//  Blue-toothLight
//
//  Created by mazg on 15/6/16.
//  Copyright (c) 2015年 mazg. All rights reserved.
//

#import "UIColorRGBValueTransformer.h"
#import <UIKit/UIKit.h>

/*本类的主要作用是在数据库中保存颜色信息,颜色是UIColor，不是数据库所规定的类，需要另外特别处理*/

@implementation UIColorRGBValueTransformer

+ (Class)transformedValueClass
{
    return [NSData class];
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)transformedValue:(id)value
{
    UIColor* color = value;
    const CGFloat* components = CGColorGetComponents(color.CGColor);
    NSString* colorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", components[0], components[1], components[2], components[3]];
    return [colorAsString dataUsingEncoding:NSUTF8StringEncoding];
}

- (id)reverseTransformedValue:(id)value
{
    NSString* colorAsString = [[NSString alloc] initWithData:value encoding:NSUTF8StringEncoding];
    NSArray* components = [colorAsString componentsSeparatedByString:@","];
    CGFloat r = [[components objectAtIndex:0] floatValue];
    CGFloat g = [[components objectAtIndex:1] floatValue];
    CGFloat b = [[components objectAtIndex:2] floatValue];
    CGFloat a = [[components objectAtIndex:3] floatValue];
    
    return [UIColor colorWithRed:r green:g blue:b alpha:a];
}


@end
